package com.hnhs.advice;

import cn.hutool.json.JSONUtil;
import com.hnhs.dto.ResponseDTO;
import com.hnhs.exception.BizException;
import com.hnhs.info.PageInfo;
import com.hnhs.threadlocalutil.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

//针对 controller 增强
@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    //支持开启增强的方法 默认是关闭
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }
    //失败回调
    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof BizException){
            BizException bizException=(BizException)ex;
            return ResponseDTO.error(
                    bizException.getCode(),
                    ex.getMessage()
            );
        }
        ResponseDTO dto=ResponseDTO.error(886, ex.getMessage());
        return dto;
    }


    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if(body instanceof ResponseDTO){
            return body;
        }
        ResponseDTO dto=ResponseDTO.success(body);
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if(pageInfo !=null){
            Map<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",body);
            dto=ResponseDTO.success(map);
            LocalPageInfoUtil.remove();
        }
        //证明接口返回的是String
        if(aClass == StringHttpMessageConverter.class){
            //改成json字符串
            return JSONUtil.toJsonStr(dto);
        }
       // 增强 响应数据的增强
        return dto;
    }
}
